package com.gws.ievent.service;

import com.alibaba.fastjson.JSON;
import com.gws.ievent.common.enums.YesOrNoEnum;
import com.gws.ievent.db.model.EventModel;
import com.gws.ievent.db.modelenum.EventJobTypeEnum;
import com.gws.ievent.scheduler.Scheduler;
import com.gws.ievent.service.job.HttpPostJob;
import com.gws.ievent.scheduler.Trigger;


/**
 * @author song
 * @date 2022/10/23 9:56
 */
public class EventManageService {

    /**
     * 添加事件
     *
     * @param model
     */
    public static void add(EventModel model) {
        Scheduler scheduler = modelTo(model);

        // 添加任务
        Trigger.getInstance().add(scheduler);
    }


    /**
     * 取消事件
     *
     * @param id
     */
    public static void cancel(long id) {
        Trigger.getInstance().cancel(id);
    }


    /**
     * 实体转化为事件
     *
     * @param model
     * @return
     */
    private static Scheduler modelTo(EventModel model) {
        Scheduler event = new Scheduler();
        event.setId(model.getId());
        event.setName(model.getName());
        event.setTimeType(model.getTimeType());
        event.setTime(model.getTime());
        event.setCancel(model.getCancel().equals(YesOrNoEnum.YES.getValue()));

        if (model.getJobType().equals(EventJobTypeEnum.HTTP_POST.getType())) {
            Object body = JSON.parse(model.getJobParam());
            if (body == null) {
                body = new Object();
            }

            HttpPostJob job = new HttpPostJob(model.getJobAddr(), body);
            event.setJob(job);
        }

        return event;
    }

}
